import React, { useState, useEffect, useRef } from 'react'
// 引入卡片
import { Card, Breadcrumb, Form, Button, Radio, DatePicker, Table, Space, Tag } from 'antd';
// 导入字体图标
import { SearchOutlined, DeleteOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom';
// 导入请求接口
// import { getChannels } from 'api/channels';
import { getArticles, delArticles } from 'api/articles';

import { Modal } from 'antd';
import Channels from 'pages/Channels';
import history from 'utils/history';
const { confirm } = Modal;



export default function ArticleList() {
    // 用于UI更新的数据用 useState 定义
    // 没有直接用于UI更新的数据用 useRef 定义
    // 1️⃣创建一个 ref 对象，用于存放 query 数据，方便在不同的函数内存值或取值
    const questref = useRef({})
    // 获取表单数据
    const onFinish = ({ status, channel_id, date }) => {
        const params = {}
        params.status = status !== -1 ? status : undefined
        params.channel_id = channel_id
        if (date) {
            // console.log('时间', date[0].format('YYYY-MM-DD HH:MM:SS'));
            params.begin_pubdate = date[0].format('YYYY-MM-DD HH:MM:SS')
            params.end_pubdate = date[1].format('YYYY-MM-DD HH:MM:SS')
        }
        console.log({ status, channel_id, date });
        // 筛选传undefined的值
        for (const key in params) {
            if (params[key] === undefined) {
                delete params[key]
            }
        }
        // console.log(params);
        // 发起请求
        getArticlesFn(params)
        // 2️⃣把表单获取的参数存储到 ref 对象中，在分页器函数中获取
        // console.log(questref.current);
        questref.current = params
    }


    // 定义频道列表
    // const [channels, setchannels] = useState([])
    // 定义文章列表
    const [articles, setarticles] = useState({})



    // 定义封装请求函数
    // const getChannelsFn = async () => {
    //     const res = await getChannels()
    //     // 修改值
    //     await setchannels(res.data.channels)
    //     // console.log(res.data);
    // }
    const getArticlesFn = async (query) => {
        const res = await getArticles(query)
        // console.log('文章', res);
        setarticles(res.data)
    }

    // 点击删除按钮
    const delArticlesFn = (id) => {
        // 二次请求
        confirm({
            title: '你确定删除该文章吗？',
            icon: <ExclamationCircleOutlined />,
            content: '温馨小提示',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            async onOk() {
                await delArticles(id)
                // 更新数据
                getArticlesFn({ ...questref.current })
            }
        });
    }

    // 定义更改页码
    const listChangeFn = (page, per_page) => {
        // console.log({ page, per_page });
        // 发起请求
        getArticlesFn({ ...questref.current, page, per_page })
    }
    // 挂载发起请求
    useEffect(() => {
        // console.log('21', channels);
        // 频道列表
        // getChannelsFn()
        // 文章列表
        getArticlesFn()
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    // 状态枚举
    const articleStatus = [
        { id: -1, name: '全部', color: 'magenta' },
        { id: 0, name: '草稿', color: 'orange' },
        { id: 1, name: '待审核', color: 'red' },
        { id: 2, name: '审核通过', color: 'green' },
        { id: 3, name: '审核失败', color: 'cyan' },
    ]

    // 表格格式规则
    const columns = [
        {
            title: '封面',
            dataIndex: 'cover',
            render: (cover) => {
                return (
                    <img src={cover.images[0]} alt="" style={{ width: 100, height: 60, objectFit: cover }} />
                )
            }
        },
        {
            title: '描述',
            dataIndex: 'title',
            width: 280
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (status) => {
                return (
                    <Tag color={articleStatus.filter(item => item.id === status)[0].color}>{articleStatus.filter(item => item.id === status)[0].name}</Tag>
                )
            }
        },
        {
            title: '发布时间',
            dataIndex: 'pubdate',
        },
        {
            title: '阅读数',
            dataIndex: 'read_count',
        },
        {
            title: '评论数',
            dataIndex: 'comment_count',
        },
        {
            title: '点赞数',
            dataIndex: 'like_count',
        },
        {
            title: '操作',
            dataIndex: 'id',
            render: (id) => {
                return (
                    <Space>
                        <Button type="primary" shape="circle" icon={<SearchOutlined />} onClick={() => history.push(`/articlePublish/${id}`)} />
                        < Button type="primary" danger shape="circle" icon={< DeleteOutlined />} onClick={() => delArticlesFn(id)} />
                    </Space>
                )
            }
        },
    ]

    return (
        <div>
            <Card title={
                <Breadcrumb>
                    <Breadcrumb.Item>
                        <Link to='/home'>首页</Link>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>
                        内容管理
                    </Breadcrumb.Item>
                </Breadcrumb>
            }>
                <Form onFinish={onFinish} initialValues={{ status: -1 }}>
                    <Form.Item label="状态" name='status'>
                        <Radio.Group>
                            <Radio value={-1}>全部</Radio>
                            <Radio value={0}>草稿</Radio>
                            <Radio value={1}>待审核</Radio>
                            <Radio value={2}>审核通过</Radio>
                            <Radio value={3}>审核失败</Radio>
                        </Radio.Group>
                    </Form.Item>
                    {/* <Form.Item label="频道" name='channel_id' >
                        <Select placeholder="请选择文章频道" style={{ width: 150 }} allowClear>
                            {channels.map((item) => (<Select.Option value={item.name} key={item.id}>{item.name}</Select.Option>)
                            )}
                        </Select>
                    </Form.Item> */}
                    <Form.Item label="频道" name='channel_id'>
                        <Channels />
                    </Form.Item>
                    <Form.Item label="日期" name='date'>
                        <DatePicker.RangePicker />
                    </Form.Item>
                    <Form.Item >
                        <Button type="primary" htmlType='submit'>筛选</Button>
                    </Form.Item>
                </Form>
                <h3>根据条件查询一共有{articles.total_count}条匹配：</h3>
                {/* 表格 */}
                <Table rowKey='id' dataSource={articles.results} columns={columns} pagination={{ position: ['bottomCenter'], total: articles.total_count, onChange: listChangeFn, current: articles.page, pageSize: articles.per_page, }} />
            </Card>
        </div>
    )
}
